package vn.com.demand.lux.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Blank;
import jxl.write.DateFormat;
import jxl.write.DateTime;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.XMLWriter;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IColorProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.nebula.widgets.datechooser.DateChooserCombo;
import org.eclipse.nebula.widgets.formattedtext.DateFormatter;
import org.eclipse.nebula.widgets.formattedtext.FormattedText;
import org.eclipse.nebula.widgets.formattedtext.NumberFormatter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.part.ViewPart;

import vn.com.demand.lux.Activator;
import vn.com.demand.lux.model.AccountReceivableDetailBean;
import vn.com.demand.lux.model.SalesOrderBean;
import vn.com.demand.lux.preferences.PreferenceConstants;
import vn.com.demand.lux.view.contentprovider.AccountReceivableContentProvider;
import vn.com.demand.util.DpUtils;
import vn.com.demand.util.Validator;
import vn.com.demand.util.XMLUtils;
import vn.com.demand.widget.ItemSelectionCallback;
import vn.com.demand.widget.SearchableDialogActivator;
import vn.com.demand.widget.SelectItemCodeHeader;
import vn.com.demand.widget.SelectSalesOrderInforHeader;

import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

public class FinanceForPayment extends ViewPart {

	private SearchableDialogActivator liExchangeRate;
	private Button importButton;
	private Text soItemName;
	private Text soItemCode;
	private Text soSaleOrder;
	@Override
	public void dispose() {
		setLastestInfor();
		super.dispose();
	}

	private Button xmlButton;
	private Button excelButton;
	private SearchableDialogActivator liDownPayment;
	private SearchableDialogActivator liBookingFee;
	private Text ciInstallmentPeriod;
	private TableViewer tableViewer;
	private Label iaInstallmentAmountResult;
	private SearchableDialogActivator liInstallmentAmount;
	private Table table;
	private SearchableDialogActivator liVATAmount;
	private SearchableDialogActivator liInterest;
	private SearchableDialogActivator liRevenue;
	private Text iaInterest;
	private Text iaBookingFee;
	private Text iaDownPayment;
	private Text iaVATAmount;
	private Text iaRevenue;
	private SearchableDialogActivator ciResource;
	private Text ciExchangerate;
	private Text ciVAT;
	private Text ciCurrency;
	private DateChooserCombo ciDueDate;
	private DateChooserCombo ciDate;
	private Text ciCurrOurRef;
	private Text giSuspense;
	private SearchableDialogActivator giJournalCode;
	private Text giInvoiceRef;
	private Text giDivision;
	private Text giCostCenter;
	private Text giCustomerName;
	private Text giCustomerCode;
	private SearchableDialogActivator giContract;
	private NumberFormatter iaRevenueNumberFormatter;
	private FormattedText ciVATFormatText;
	private FormattedText iaVATAmoutFormatText;
	private FormattedText iaInterstFormatText;
	private FormattedText iaBookingFeeFormattedText;
	private FormattedText iaDownpaymentFormattedText;
	private Label iaInvoiceAmountResult;
	private FormattedText ciInstallmentPeriodFormatText;
	private FormattedText ciEchangeFormatText;
	private ArrayList<AccountReceivableDetailBean> list;
	public static final String ID = "vn.com.demand.lux.view.FinanceForPayment"; //$NON-NLS-1$
	
	public static final int ROUND_SCALE = 2;
	public static final int VND_ROUND_SCALE = 0;
	public static final int ROUND_MODE = BigDecimal.ROUND_HALF_UP;
	
	/**
	 * Create contents of the view part
	 * 
	 * @param parent
	 */
	@Override
	public void createPartControl(Composite parent) {
		FormToolkit toolkit = new FormToolkit(Display.getCurrent());
		Composite container = toolkit.createComposite(parent, SWT.NONE);
		container.setLayout(new FillLayout());
		toolkit.paintBordersFor(container);

		final Form luxPaymnetForm = toolkit.createForm(container);
		final Composite body = luxPaymnetForm.getBody();
		body.setLayout(new FormLayout());
		toolkit.paintBordersFor(body);

		final Composite composite = toolkit.createComposite(body, SWT.BORDER);
		final FormData fd_composite = new FormData();
		fd_composite.bottom = new FormAttachment(0, 235);
		fd_composite.right = new FormAttachment(100, 0);
		fd_composite.top = new FormAttachment(0, 0);
		fd_composite.left = new FormAttachment(0, 0);
		composite.setLayoutData(fd_composite);
		final FillLayout fillLayout = new FillLayout();
		fillLayout.spacing = 5;
		composite.setLayout(fillLayout);
		toolkit.paintBordersFor(composite);

		final Section generalInformationSection = toolkit.createSection(
				composite, Section.COMPACT | Section.TWISTIE | Section.EXPANDED
						| Section.TITLE_BAR);
		generalInformationSection.setText("General Information");

		final Composite giComposite = toolkit
				.createComposite(generalInformationSection);
		giComposite.setLayout(new FormLayout());
		generalInformationSection.setClient(giComposite);
		toolkit.paintBordersFor(giComposite);

		final Label contractLabel = toolkit.createLabel(giComposite,
				"Contract", SWT.NONE);
		final FormData fd_contractLabel = new FormData();
		fd_contractLabel.bottom = new FormAttachment(0, 19);
		fd_contractLabel.top = new FormAttachment(0, 6);
		fd_contractLabel.right = new FormAttachment(0, 50);
		fd_contractLabel.left = new FormAttachment(0, 0);
		contractLabel.setLayoutData(fd_contractLabel);
		contractLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel
				.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		final Label contractLabel_1 = toolkit.createLabel(giComposite,
				"Customer code", SWT.NONE);
		final FormData fd_contractLabel_1 = new FormData();
		fd_contractLabel_1.bottom = new FormAttachment(0, 44);
		fd_contractLabel_1.top = new FormAttachment(0, 31);
		fd_contractLabel_1.right = new FormAttachment(0, 78);
		fd_contractLabel_1.left = new FormAttachment(0, 0);
		contractLabel_1.setLayoutData(fd_contractLabel_1);
		contractLabel_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_2 = toolkit.createLabel(giComposite,
				"Customer name", SWT.NONE);
		final FormData fd_contractLabel_2 = new FormData();
		fd_contractLabel_2.bottom = new FormAttachment(0, 69);
		fd_contractLabel_2.top = new FormAttachment(0, 56);
		fd_contractLabel_2.right = new FormAttachment(0, 78);
		fd_contractLabel_2.left = new FormAttachment(0, 0);
		contractLabel_2.setLayoutData(fd_contractLabel_2);
		contractLabel_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_2.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_3 = toolkit.createLabel(giComposite,
				"Cost center", SWT.NONE);
		final FormData fd_contractLabel_3 = new FormData();
		fd_contractLabel_3.bottom = new FormAttachment(0, 94);
		fd_contractLabel_3.top = new FormAttachment(0, 81);
		fd_contractLabel_3.right = new FormAttachment(0, 62);
		fd_contractLabel_3.left = new FormAttachment(0, 0);
		contractLabel_3.setLayoutData(fd_contractLabel_3);
		contractLabel_3.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_3.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_4 = toolkit.createLabel(giComposite,
				"Division", SWT.NONE);
		final FormData fd_contractLabel_4 = new FormData();
		fd_contractLabel_4.bottom = new FormAttachment(0, 119);
		fd_contractLabel_4.top = new FormAttachment(0, 106);
		fd_contractLabel_4.right = new FormAttachment(0, 50);
		fd_contractLabel_4.left = new FormAttachment(0, 0);
		contractLabel_4.setLayoutData(fd_contractLabel_4);
		contractLabel_4.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_4.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_5 = toolkit.createLabel(giComposite,
				"Invoice Ref (*)", SWT.NONE);
		final FormData fd_contractLabel_5 = new FormData();
		fd_contractLabel_5.bottom = new FormAttachment(0, 144);
		fd_contractLabel_5.top = new FormAttachment(0, 131);
		fd_contractLabel_5.right = new FormAttachment(0, 78);
		fd_contractLabel_5.left = new FormAttachment(0, 0);
		contractLabel_5.setLayoutData(fd_contractLabel_5);
		contractLabel_5.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_5.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_6 = toolkit.createLabel(giComposite,
				"Journal code", SWT.NONE);
		final FormData fd_contractLabel_6 = new FormData();
		fd_contractLabel_6.bottom = new FormAttachment(0, 169);
		fd_contractLabel_6.top = new FormAttachment(0, 156);
		fd_contractLabel_6.right = new FormAttachment(0, 62);
		fd_contractLabel_6.left = new FormAttachment(0, 0);
		contractLabel_6.setLayoutData(fd_contractLabel_6);
		contractLabel_6.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_6.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		Label contractLabel_7;
		contractLabel_7 = toolkit.createLabel(giComposite,
				"Suspense", SWT.NONE);
		final FormData fd_contractLabel_7 = new FormData();
		fd_contractLabel_7.bottom = new FormAttachment(0, 195);
		fd_contractLabel_7.top = new FormAttachment(0, 182);
		fd_contractLabel_7.right = new FormAttachment(0, 50);
		fd_contractLabel_7.left = new FormAttachment(0, 0);
		contractLabel_7.setLayoutData(fd_contractLabel_7);
		contractLabel_7.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_7.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		SelectItemCodeHeader contractHeader = new SelectItemCodeHeader(null, "select contractnumber, contractdescription from DEMAND_AccountReceivableContractSelection order by contractnumber");
		giContract = new SearchableDialogActivator(giComposite, SWT.NONE, contractHeader);
		final FormData fd_giContract = new FormData();
		fd_giContract.right = new FormAttachment(100, -9);
		fd_giContract.bottom = new FormAttachment(0, 26);
		fd_giContract.top = new FormAttachment(0, 6);
		fd_giContract.left = new FormAttachment(0, 78);
		giContract.setLayoutData(fd_giContract);
		giContract.setItemSelectedHandler(new ItemSelectionCallback(){

			public void itemSelectedHandler(String selectedItem) {
				doFillContractInforAndClearOldResult();
				doFillSalesOrderInformation();
			}
			
		});
		
		giCustomerCode = toolkit.createText(giComposite, null, SWT.NONE);
		final FormData fd_giCustomerCode = new FormData();
		fd_giCustomerCode.right = new FormAttachment(100, -9);
		fd_giCustomerCode.bottom = new FormAttachment(0, 50);
		fd_giCustomerCode.top = new FormAttachment(0, 31);
		fd_giCustomerCode.left = new FormAttachment(0, 78);
		giCustomerCode.setLayoutData(fd_giCustomerCode);
		giCustomerCode.setEditable(false);

		giCustomerName = toolkit.createText(giComposite, null, SWT.NONE);
		final FormData fd_giCustomerName = new FormData();
		fd_giCustomerName.right = new FormAttachment(100, -9);
		fd_giCustomerName.bottom = new FormAttachment(0, 75);
		fd_giCustomerName.top = new FormAttachment(0, 56);
		fd_giCustomerName.left = new FormAttachment(0, 78);
		giCustomerName.setLayoutData(fd_giCustomerName);
		giCustomerName.setEditable(false);

		giCostCenter = toolkit.createText(giComposite, null, SWT.NONE);
		final FormData fd_giCostCenter = new FormData();
		fd_giCostCenter.right = new FormAttachment(100, -9);
		fd_giCostCenter.bottom = new FormAttachment(0, 100);
		fd_giCostCenter.top = new FormAttachment(0, 81);
		fd_giCostCenter.left = new FormAttachment(0, 78);
		giCostCenter.setLayoutData(fd_giCostCenter);
		giCostCenter.setEditable(false);

		giDivision = toolkit.createText(giComposite, null, SWT.NONE);
		final FormData fd_giDivision = new FormData();
		fd_giDivision.right = new FormAttachment(100, -9);
		fd_giDivision.bottom = new FormAttachment(0, 125);
		fd_giDivision.top = new FormAttachment(0, 106);
		fd_giDivision.left = new FormAttachment(0, 78);
		giDivision.setLayoutData(fd_giDivision);
		giDivision.setText(PreferenceConstants.ACCOUNT_RECEIVABLE_DIVISION);

		giInvoiceRef = toolkit.createText(giComposite, null, SWT.NONE);
		final FormData fd_giInvoiceRef = new FormData();
		fd_giInvoiceRef.right = new FormAttachment(100, -9);
		fd_giInvoiceRef.bottom = new FormAttachment(0, 150);
		fd_giInvoiceRef.top = new FormAttachment(0, 131);
		fd_giInvoiceRef.left = new FormAttachment(0, 78);
		giInvoiceRef.setLayoutData(fd_giInvoiceRef);

		SelectItemCodeHeader journalHeader = new SelectItemCodeHeader(null,
				"select * from DEMAND_JournalList order by journalcode");
		giJournalCode = new SearchableDialogActivator(giComposite, SWT.NONE,
				journalHeader);
		final FormData fd_giJournalCode = new FormData();
		fd_giJournalCode.right = new FormAttachment(100, -9);
		fd_giJournalCode.bottom = new FormAttachment(0, 176);
		fd_giJournalCode.top = new FormAttachment(0, 156);
		fd_giJournalCode.left = new FormAttachment(0, 78);
		giJournalCode.setLayoutData(fd_giJournalCode);
		giJournalCode.setText("530");

		giSuspense = toolkit.createText(giComposite, null, SWT.NONE);
		final FormData fd_giSuspense = new FormData();
		fd_giSuspense.right = new FormAttachment(100, -9);
		fd_giSuspense.bottom = new FormAttachment(0, 201);
		fd_giSuspense.top = new FormAttachment(0, 182);
		fd_giSuspense.left = new FormAttachment(0, 78);
		giSuspense.setLayoutData(fd_giSuspense);
		giSuspense.setEditable(false);
		giSuspense.setText("999999");

		final Section installmentConditionSection = toolkit.createSection(
				composite, Section.TWISTIE | Section.EXPANDED
						| Section.TITLE_BAR | Section.FOCUS_TITLE);
		installmentConditionSection.setText("Installment Condition");

		final Composite icComposite = toolkit
				.createComposite(installmentConditionSection);
		icComposite.setLayout(new FormLayout());
		installmentConditionSection.setClient(icComposite);
		toolkit.paintBordersFor(icComposite);

		final Label contractLabel_9 = toolkit.createLabel(icComposite, "Date",
				SWT.NONE);
		final FormData fd_contractLabel_9 = new FormData();
		fd_contractLabel_9.bottom = new FormAttachment(0, 17);
		fd_contractLabel_9.top = new FormAttachment(0, 4);
		fd_contractLabel_9.right = new FormAttachment(0, 40);
		fd_contractLabel_9.left = new FormAttachment(0, 0);
		contractLabel_9.setLayoutData(fd_contractLabel_9);
		contractLabel_9.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_9.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		ciDate = new DateChooserCombo(icComposite, SWT.BORDER);
		final FormData fd_ciDate = new FormData();
		fd_ciDate.right = new FormAttachment(100, -5);
		fd_ciDate.bottom = new FormAttachment(0, 23);
		fd_ciDate.top = new FormAttachment(0, 4);
		fd_ciDate.left = new FormAttachment(0, 94);
		ciDate.setLayoutData(fd_ciDate);
		DateFormatter dateFormatter = new DateFormatter(Activator.getDefault()
				.getDateFormatTypePreferences());
		ciDate.setFormatter(dateFormatter);
		ciDate.setValue(new Date(System.currentTimeMillis()));

		final Label contractLabel_1_1 = toolkit.createLabel(icComposite,
				"First due date", SWT.NONE);
		final FormData fd_contractLabel_1_1 = new FormData();
		fd_contractLabel_1_1.bottom = new FormAttachment(0, 42);
		fd_contractLabel_1_1.top = new FormAttachment(0, 29);
		fd_contractLabel_1_1.right = new FormAttachment(0, 70);
		fd_contractLabel_1_1.left = new FormAttachment(0, 0);
		contractLabel_1_1.setLayoutData(fd_contractLabel_1_1);
		contractLabel_1_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		ciDueDate = new DateChooserCombo(icComposite, SWT.BORDER);
		final FormData fd_ciDueDate = new FormData();
		fd_ciDueDate.right = new FormAttachment(100, -5);
		fd_ciDueDate.bottom = new FormAttachment(0, 48);
		fd_ciDueDate.top = new FormAttachment(0, 29);
		fd_ciDueDate.left = new FormAttachment(0, 94);
		ciDueDate.setLayoutData(fd_ciDueDate);
		DateFormatter dueDateFormatter = new DateFormatter(Activator
				.getDefault().getDateFormatTypePreferences());
		ciDueDate.setFormatter(dueDateFormatter);
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date(System.currentTimeMillis()));
		cal.add(Calendar.MONTH, 1);
		ciDueDate.setValue(cal.getTime());

		ciCurrency = toolkit.createText(icComposite, null, SWT.NONE);
		final FormData fd_ciCurrency = new FormData();
		fd_ciCurrency.right = new FormAttachment(100, -5);
		fd_ciCurrency.bottom = new FormAttachment(0, 123);
		fd_ciCurrency.top = new FormAttachment(0, 104);
		fd_ciCurrency.left = new FormAttachment(0, 94);
		ciCurrency.setLayoutData(fd_ciCurrency);
		ciCurrency.setText("USD");

		ciVAT = toolkit.createText(icComposite, null, SWT.NONE);
		final FormData fd_ciVAT = new FormData();
		fd_ciVAT.right = new FormAttachment(100, -5);
		fd_ciVAT.bottom = new FormAttachment(0, 98);
		fd_ciVAT.top = new FormAttachment(0, 79);
		fd_ciVAT.left = new FormAttachment(0, 94);
		ciVAT.setLayoutData(fd_ciVAT);
		ciVATFormatText = new FormattedText(ciVAT);
		NumberFormatter ciVATNumberFormat = new NumberFormatter("###");
		ciVATFormatText.setFormatter(ciVATNumberFormat);
		ciVATFormatText.setValue(10);

		final Label contractLabel_4_1 = toolkit.createLabel(icComposite,
				"VAT percentage", SWT.NONE);
		final FormData fd_contractLabel_4_1 = new FormData();
		fd_contractLabel_4_1.bottom = new FormAttachment(0, 92);
		fd_contractLabel_4_1.top = new FormAttachment(0, 79);
		fd_contractLabel_4_1.right = new FormAttachment(0, 85);
		fd_contractLabel_4_1.left = new FormAttachment(0, 0);
		contractLabel_4_1.setLayoutData(fd_contractLabel_4_1);
		contractLabel_4_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_4_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_5_1 = toolkit.createLabel(icComposite,
				"Currency", SWT.NONE);
		final FormData fd_contractLabel_5_1 = new FormData();
		fd_contractLabel_5_1.bottom = new FormAttachment(0, 117);
		fd_contractLabel_5_1.top = new FormAttachment(0, 104);
		fd_contractLabel_5_1.right = new FormAttachment(0, 50);
		fd_contractLabel_5_1.left = new FormAttachment(0, 0);
		contractLabel_5_1.setLayoutData(fd_contractLabel_5_1);
		contractLabel_5_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_5_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_6_1 = toolkit.createLabel(icComposite,
				"Exchange rate", SWT.NONE);
		final FormData fd_contractLabel_6_1 = new FormData();
		fd_contractLabel_6_1.bottom = new FormAttachment(0, 142);
		fd_contractLabel_6_1.top = new FormAttachment(0, 129);
		fd_contractLabel_6_1.right = new FormAttachment(0, 78);
		fd_contractLabel_6_1.left = new FormAttachment(0, 0);
		contractLabel_6_1.setLayoutData(fd_contractLabel_6_1);
		contractLabel_6_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_6_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		ciExchangerate = toolkit.createText(icComposite, null, SWT.NONE);
		final FormData fd_ciExchangerate = new FormData();
		fd_ciExchangerate.right = new FormAttachment(100, -5);
		fd_ciExchangerate.bottom = new FormAttachment(0, 148);
		fd_ciExchangerate.top = new FormAttachment(0, 129);
		fd_ciExchangerate.left = new FormAttachment(0, 94);
		ciExchangerate.setLayoutData(fd_ciExchangerate);
		ciEchangeFormatText = new FormattedText(ciExchangerate);
		NumberFormatter ciExchangeNumberFormat = new NumberFormatter(
				"###,###,###.00");
		ciEchangeFormatText.setFormatter(ciExchangeNumberFormat);
		ciEchangeFormatText.setValue(16000);

		final Label contractLabel_7_1 = toolkit.createLabel(icComposite,
				"Resource", SWT.NONE);
		final FormData fd_contractLabel_7_1 = new FormData();
		fd_contractLabel_7_1.bottom = new FormAttachment(0, 167);
		fd_contractLabel_7_1.top = new FormAttachment(0, 154);
		fd_contractLabel_7_1.right = new FormAttachment(0, 60);
		fd_contractLabel_7_1.left = new FormAttachment(0, 0);
		contractLabel_7_1.setLayoutData(fd_contractLabel_7_1);
		contractLabel_7_1.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_7_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		SelectItemCodeHeader resourceHeader = new SelectItemCodeHeader(null, "select res_id as code , fullname as description from DEMAND_ResourceList");

		Label contractLabel_4_1_1;
		contractLabel_4_1_1 = toolkit.createLabel(icComposite,
				"Installment (month)", SWT.NONE);
		final FormData fd_contractLabel_4_1_1 = new FormData();
		fd_contractLabel_4_1_1.bottom = new FormAttachment(0, 67);
		fd_contractLabel_4_1_1.top = new FormAttachment(0, 54);
		fd_contractLabel_4_1_1.right = new FormAttachment(0, 94);
		fd_contractLabel_4_1_1.left = new FormAttachment(0, 0);
		contractLabel_4_1_1.setLayoutData(fd_contractLabel_4_1_1);
		contractLabel_4_1_1.setForeground(SWTResourceManager
				.getColor(0, 0, 255));
		contractLabel_4_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		ciInstallmentPeriod = toolkit.createText(icComposite, null, SWT.NONE);
		final FormData fd_ciInstallmentPeriod = new FormData();
		fd_ciInstallmentPeriod.right = new FormAttachment(100, -5);
		fd_ciInstallmentPeriod.bottom = new FormAttachment(0, 73);
		fd_ciInstallmentPeriod.top = new FormAttachment(0, 54);
		fd_ciInstallmentPeriod.left = new FormAttachment(0, 94);
		ciInstallmentPeriod.setLayoutData(fd_ciInstallmentPeriod);
		ciInstallmentPeriodFormatText = new FormattedText(ciInstallmentPeriod);

		final Label contractLabel_8 = toolkit.createLabel(icComposite,
				"Current Our Ref", SWT.NONE);
		final FormData fd_contractLabel_8 = new FormData();
		fd_contractLabel_8.bottom = new FormAttachment(0, 193);
		fd_contractLabel_8.top = new FormAttachment(0, 180);
		fd_contractLabel_8.right = new FormAttachment(0, 85);
		fd_contractLabel_8.left = new FormAttachment(0, 0);
		contractLabel_8.setLayoutData(fd_contractLabel_8);
		contractLabel_8.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_8.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		ciCurrOurRef = toolkit.createText(icComposite, null, SWT.NONE);
		final FormData fd_ciCurrOurRef = new FormData();
		fd_ciCurrOurRef.right = new FormAttachment(100, -5);
		fd_ciCurrOurRef.bottom = new FormAttachment(0, 199);
		fd_ciCurrOurRef.top = new FormAttachment(0, 180);
		fd_ciCurrOurRef.left = new FormAttachment(0, 94);
		ciCurrOurRef.setLayoutData(fd_ciCurrOurRef);
		ciCurrOurRef.setText(DpUtils.trim(getCurrentOurRef()));
		
		ciResource = new SearchableDialogActivator(icComposite, SWT.NONE, resourceHeader);
		final FormData fd_ciResource = new FormData();
		fd_ciResource.right = new FormAttachment(100, -5);
		fd_ciResource.bottom = new FormAttachment(0, 174);
		fd_ciResource.top = new FormAttachment(0, 154);
		fd_ciResource.left = new FormAttachment(0, 94);
		ciResource.setLayoutData(fd_ciResource);
		NumberFormatter ciInstallmentPeriodNumberFormat = new NumberFormatter(
				"##");
		ciInstallmentPeriodFormatText
				.setFormatter(ciInstallmentPeriodNumberFormat);
		ciInstallmentPeriodFormatText.setValue(12);

		final Section invoiceAmountSection = toolkit.createSection(composite,
				Section.TWISTIE | Section.EXPANDED | Section.TITLE_BAR
						| Section.FOCUS_TITLE);
		invoiceAmountSection.setText("Invoice Amount");

		final Composite iaComposite = toolkit.createComposite(
				invoiceAmountSection, SWT.EMBEDDED);
		iaComposite.setLayout(new FormLayout());
		invoiceAmountSection.setClient(iaComposite);
		toolkit.paintBordersFor(iaComposite);

		final Label contractLabel_10 = toolkit.createLabel(iaComposite,
				"Revenue", SWT.NONE);
		final FormData fd_contractLabel_10 = new FormData();
		fd_contractLabel_10.bottom = new FormAttachment(0, 17);
		fd_contractLabel_10.top = new FormAttachment(0, 4);
		fd_contractLabel_10.right = new FormAttachment(0, 60);
		fd_contractLabel_10.left = new FormAttachment(0, 10);
		contractLabel_10.setLayoutData(fd_contractLabel_10);
		contractLabel_10.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_10.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		iaRevenue = toolkit.createText(iaComposite, null, SWT.RIGHT);
		final FormData fd_iaRevenue = new FormData();
		fd_iaRevenue.right = new FormAttachment(100, -12);
		fd_iaRevenue.bottom = new FormAttachment(0, 23);
		fd_iaRevenue.top = new FormAttachment(0, 4);
		fd_iaRevenue.left = new FormAttachment(0, 88);
		iaRevenue.setLayoutData(fd_iaRevenue);
		FormattedText formattedText = new FormattedText(iaRevenue);
		iaRevenueNumberFormatter = new NumberFormatter("###,###,###,###.##");
		formattedText.setFormatter(iaRevenueNumberFormatter);
		iaRevenue.addFocusListener(new FocusListener() {

			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				caculateVATAmount();
				refreshAmount();
			}

		});

		iaVATAmount = toolkit.createText(iaComposite, null, SWT.RIGHT);
		final FormData fd_iaVATAmount = new FormData();
		fd_iaVATAmount.right = new FormAttachment(100, -12);
		fd_iaVATAmount.bottom = new FormAttachment(0, 48);
		fd_iaVATAmount.top = new FormAttachment(0, 29);
		fd_iaVATAmount.left = new FormAttachment(0, 88);
		iaVATAmount.setLayoutData(fd_iaVATAmount);
		iaVATAmoutFormatText = new FormattedText(iaVATAmount);
		NumberFormatter vatAmountNumberFormat = new NumberFormatter(
				"###,###,###,###.##");
		iaVATAmoutFormatText.setFormatter(vatAmountNumberFormat);
		iaVATAmount.addFocusListener(new FocusListener() {

			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				refreshAmount();
			}

		});

		final Label contractLabel_1_2 = toolkit.createLabel(iaComposite,
				"VAT Amount", SWT.NONE);
		final FormData fd_contractLabel_1_2 = new FormData();
		fd_contractLabel_1_2.bottom = new FormAttachment(0, 42);
		fd_contractLabel_1_2.top = new FormAttachment(0, 29);
		fd_contractLabel_1_2.right = new FormAttachment(0, 72);
		fd_contractLabel_1_2.left = new FormAttachment(0, 10);
		contractLabel_1_2.setLayoutData(fd_contractLabel_1_2);
		contractLabel_1_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_1_2.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_2_2 = toolkit.createLabel(iaComposite,
				"Interest", SWT.NONE);
		final FormData fd_contractLabel_2_2 = new FormData();
		fd_contractLabel_2_2.bottom = new FormAttachment(0, 67);
		fd_contractLabel_2_2.top = new FormAttachment(0, 54);
		fd_contractLabel_2_2.right = new FormAttachment(0, 60);
		fd_contractLabel_2_2.left = new FormAttachment(0, 10);
		contractLabel_2_2.setLayoutData(fd_contractLabel_2_2);
		contractLabel_2_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_2_2.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		Label contractLabel_3_2;
		contractLabel_3_2 = toolkit.createLabel(iaComposite,
				"Booking fee", SWT.NONE);
		final FormData fd_contractLabel_3_2 = new FormData();
		fd_contractLabel_3_2.bottom = new FormAttachment(0, 92);
		fd_contractLabel_3_2.top = new FormAttachment(0, 79);
		fd_contractLabel_3_2.right = new FormAttachment(0, 72);
		fd_contractLabel_3_2.left = new FormAttachment(0, 10);
		contractLabel_3_2.setLayoutData(fd_contractLabel_3_2);
		contractLabel_3_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_3_2.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		Label contractLabel_4_2;
		contractLabel_4_2 = toolkit.createLabel(iaComposite,
				"Down payment", SWT.NONE);
		final FormData fd_contractLabel_4_2 = new FormData();
		fd_contractLabel_4_2.bottom = new FormAttachment(0, 117);
		fd_contractLabel_4_2.top = new FormAttachment(0, 104);
		fd_contractLabel_4_2.right = new FormAttachment(0, 88);
		fd_contractLabel_4_2.left = new FormAttachment(0, 10);
		contractLabel_4_2.setLayoutData(fd_contractLabel_4_2);
		contractLabel_4_2.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_4_2.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));
		
		iaInterest = toolkit.createText(iaComposite, null, SWT.RIGHT);
		final FormData fd_iaInterest = new FormData();
		fd_iaInterest.right = new FormAttachment(100, -12);
		fd_iaInterest.bottom = new FormAttachment(0, 73);
		fd_iaInterest.top = new FormAttachment(0, 54);
		fd_iaInterest.left = new FormAttachment(0, 88);
		iaInterest.setLayoutData(fd_iaInterest);
		iaInterstFormatText = new FormattedText(iaInterest);
		NumberFormatter interestNumberFormat = new NumberFormatter(
				"###,###,###,###.##");
		iaInterstFormatText.setFormatter(interestNumberFormat);
		iaInterest.addFocusListener(new FocusListener() {

			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				refreshAmount();
			}

		});
		
		iaBookingFee = toolkit.createText(iaComposite, null, SWT.RIGHT);
		final FormData fd_iaBookingFee = new FormData();
		fd_iaBookingFee.right = new FormAttachment(100, -12);
		fd_iaBookingFee.bottom = new FormAttachment(0, 98);
		fd_iaBookingFee.top = new FormAttachment(0, 79);
		fd_iaBookingFee.left = new FormAttachment(0, 88);
		iaBookingFee.setLayoutData(fd_iaBookingFee);
		iaBookingFeeFormattedText = new FormattedText(iaBookingFee);
		NumberFormatter bookingFeeNumberFormat = new NumberFormatter(
				"###,###,###,###.##");
		iaBookingFeeFormattedText.setFormatter(bookingFeeNumberFormat);
		iaBookingFee.addFocusListener(new FocusListener() {

			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				refreshAmount();
			}

		});
		
		iaDownPayment = toolkit.createText(iaComposite, null, SWT.RIGHT);
		final FormData fd_iaDownPayment = new FormData();
		fd_iaDownPayment.right = new FormAttachment(100, -12);
		fd_iaDownPayment.bottom = new FormAttachment(0, 123);
		fd_iaDownPayment.top = new FormAttachment(0, 104);
		fd_iaDownPayment.left = new FormAttachment(0, 88);
		iaDownPayment.setLayoutData(fd_iaDownPayment);
		iaDownpaymentFormattedText = new FormattedText(iaDownPayment);
		NumberFormatter downPaymentFormat = new NumberFormatter(
				"###,###,###,###.##");
		iaDownpaymentFormattedText.setFormatter(downPaymentFormat);
		iaDownPayment.addFocusListener(new FocusListener() {

			public void focusGained(FocusEvent e) {
			}

			public void focusLost(FocusEvent e) {
				refreshAmount();
			}

		});
		
		Label label;
		label = new Label(iaComposite, SWT.SEPARATOR
				| SWT.HORIZONTAL);
		final FormData fd_label = new FormData();
		fd_label.bottom = new FormAttachment(0, 144);
		fd_label.top = new FormAttachment(0, 131);
		fd_label.right = new FormAttachment(0, 222);
		fd_label.left = new FormAttachment(0, 45);
		label.setLayoutData(fd_label);
		toolkit.adapt(label, true, true);

		final Label invoiceAmountLabel = toolkit.createLabel(iaComposite,
				"Invoice Amount:", SWT.NONE);
		final FormData fd_invoiceAmountLabel = new FormData();
		fd_invoiceAmountLabel.bottom = new FormAttachment(0, 167);
		fd_invoiceAmountLabel.top = new FormAttachment(0, 154);
		fd_invoiceAmountLabel.right = new FormAttachment(0, 100);
		fd_invoiceAmountLabel.left = new FormAttachment(0, 0);
		invoiceAmountLabel.setLayoutData(fd_invoiceAmountLabel);
		invoiceAmountLabel
				.setForeground(SWTResourceManager.getColor(0, 0, 255));
		invoiceAmountLabel.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.BOLD));

		iaInvoiceAmountResult = toolkit.createLabel(iaComposite, "0", SWT.NONE);
		final FormData fd_iaInvoiceAmountResult = new FormData();
		fd_iaInvoiceAmountResult.right = new FormAttachment(100, -12);
		fd_iaInvoiceAmountResult.bottom = new FormAttachment(0, 167);
		fd_iaInvoiceAmountResult.top = new FormAttachment(0, 154);
		fd_iaInvoiceAmountResult.left = new FormAttachment(0, 117);
		iaInvoiceAmountResult.setLayoutData(fd_iaInvoiceAmountResult);
		iaInvoiceAmountResult.setAlignment(SWT.RIGHT);
		iaInvoiceAmountResult.setForeground(SWTResourceManager.getColor(0, 0,
				255));
		iaInvoiceAmountResult.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.BOLD));

		Label installmentAmount;
		installmentAmount = toolkit.createLabel(iaComposite,
				"Installment Amount:", SWT.NONE);
		final FormData fd_installmentAmount = new FormData();
		fd_installmentAmount.bottom = new FormAttachment(0, 193);
		fd_installmentAmount.top = new FormAttachment(0, 180);
		fd_installmentAmount.right = new FormAttachment(0, 117);
		fd_installmentAmount.left = new FormAttachment(0, 0);
		installmentAmount.setLayoutData(fd_installmentAmount);
		installmentAmount.setForeground(SWTResourceManager.getColor(0, 0, 255));
		installmentAmount.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.BOLD));

		iaInstallmentAmountResult = toolkit.createLabel(iaComposite, "0",
				SWT.NONE);
		final FormData fd_iaInstallmentAmountResult = new FormData();
		fd_iaInstallmentAmountResult.right = new FormAttachment(100, -12);
		fd_iaInstallmentAmountResult.bottom = new FormAttachment(0, 193);
		fd_iaInstallmentAmountResult.top = new FormAttachment(0, 180);
		fd_iaInstallmentAmountResult.left = new FormAttachment(0, 117);
		iaInstallmentAmountResult.setLayoutData(fd_iaInstallmentAmountResult);
		iaInstallmentAmountResult.setForeground(SWTResourceManager.getColor(0,
				0, 255));
		iaInstallmentAmountResult.setFont(SWTResourceManager.getFont("Tahoma",
				8, SWT.BOLD));
		iaInstallmentAmountResult.setAlignment(SWT.RIGHT);

		final Section ledgerInSection = toolkit.createSection(composite,
				Section.TWISTIE | Section.EXPANDED | Section.TITLE_BAR
						| Section.FOCUS_TITLE);
		ledgerInSection.setText("Ledger Information");

		final Composite liComposite = toolkit.createComposite(ledgerInSection);
		ledgerInSection.setClient(liComposite);
		toolkit.paintBordersFor(liComposite);
		
		SelectItemCodeHeader revenueHeader = new SelectItemCodeHeader(null, "select * from DEMAND_LedgerListRevenue");
		liRevenue = new SearchableDialogActivator(liComposite, SWT.NONE, revenueHeader);
		liRevenue.setBounds(97, 4, 117, 20);
		liRevenue.setText("511001");

		final Label contractLabel_10_1 = toolkit.createLabel(liComposite,
				"Revenue", SWT.NONE);
		contractLabel_10_1.setBounds(0, 4, 50, 13);
		contractLabel_10_1
				.setForeground(SWTResourceManager.getColor(0, 0, 255));
		contractLabel_10_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_1_2_1 = toolkit.createLabel(liComposite,
				"VAT Amount", SWT.NONE);
		contractLabel_1_2_1.setBounds(0, 57, 62, 13);
		contractLabel_1_2_1.setForeground(SWTResourceManager
				.getColor(0, 0, 255));
		contractLabel_1_2_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label contractLabel_2_2_1 = toolkit.createLabel(liComposite,
				"Interest", SWT.NONE);
		contractLabel_2_2_1.setBounds(0, 82, 50, 13);
		contractLabel_2_2_1.setForeground(SWTResourceManager
				.getColor(0, 0, 255));
		contractLabel_2_2_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));
		SelectItemCodeHeader interestHeader = new SelectItemCodeHeader(null, "select * from DEMAND_LedgerListDefferRevenue");
		liInterest = new SearchableDialogActivator(liComposite, SWT.NONE, interestHeader);
		liInterest.setBounds(97, 82, 117, 20);
		liInterest.setText(PreferenceConstants.ACCOUNT_RECEIVABLE_INTEREST);
		
		SelectItemCodeHeader vatAmoutHeader = new SelectItemCodeHeader(null, "select * from DEMAND_LedgerListVATOutput");
		liVATAmount = new SearchableDialogActivator(liComposite, SWT.NONE, vatAmoutHeader);
		liVATAmount.setBounds(97, 57, 117, 20);
		liVATAmount.setText(PreferenceConstants.ACCOUNT_RECEIVABLE_VAT_AMOUNT);
		
		SelectItemCodeHeader header = new SelectItemCodeHeader(null, "select * from DEMAND_LedgerListAR");
		liInstallmentAmount = new SearchableDialogActivator(liComposite, SWT.NONE, header);
		liInstallmentAmount.setBounds(97, 157, 117, 20);
		liInstallmentAmount.setText(PreferenceConstants.ACCOUNT_RECEIVABLE_INSTALLMENT_AMOUNT);

		Label contractLabel_2_2_1_1;
		contractLabel_2_2_1_1 = toolkit.createLabel(liComposite,
				"Installment Amount", SWT.NONE);
		contractLabel_2_2_1_1.setBounds(0, 157, 92, 13);
		contractLabel_2_2_1_1.setForeground(SWTResourceManager.getColor(0, 0,
				255));
		contractLabel_2_2_1_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));
		
		liBookingFee = new SearchableDialogActivator(liComposite, SWT.NONE, header);
		liBookingFee.setBounds(97, 107, 117, 20);
		liBookingFee.setText("131203");

		liDownPayment = new SearchableDialogActivator(liComposite, SWT.NONE, header);
		liDownPayment.setBounds(97, 132, 117, 20);
		liDownPayment.setText("131202");

		Label contractLabel_4_2_1;
		contractLabel_4_2_1 = toolkit.createLabel(liComposite, "Down payment",
				SWT.NONE);
		contractLabel_4_2_1.setBounds(0, 132, 78, 13);
		contractLabel_4_2_1.setForeground(SWTResourceManager
				.getColor(0, 0, 255));
		contractLabel_4_2_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		Label contractLabel_3_2_1;
		contractLabel_3_2_1 = toolkit.createLabel(liComposite,
				"Booking fee", SWT.NONE);
		contractLabel_3_2_1.setBounds(0, 107, 62, 13);
		contractLabel_3_2_1.setForeground(SWTResourceManager
				.getColor(0, 0, 255));
		contractLabel_3_2_1.setFont(SWTResourceManager.getFont("Tahoma", 8,
				SWT.NONE));

		final Label liExhangerateLabel = toolkit.createLabel(liComposite, "Exchange rate", SWT.NONE);
		liExhangerateLabel.setBounds(0, 30, 78, 13);
		liExhangerateLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		liExhangerateLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));
		
		SelectItemCodeHeader exchageHeader = new SelectItemCodeHeader(null, "select reknr as code, oms25_0 as description from demand_ledgerlistexchangerate");
		liExchangeRate = new SearchableDialogActivator(liComposite, SWT.NONE, exchageHeader);
		liExchangeRate.setBounds(97, 30, 117, 20);
		liExchangeRate.setText("635004");
		toolkit.adapt(liExchangeRate);

		final Section saleOrderInformationSection = toolkit.createSection(composite, Section.TWISTIE | Section.EXPANDED | Section.TITLE_BAR | Section.FOCUS_TITLE);
		saleOrderInformationSection.setText("Sales Order Information");

		final Composite soComposite = new Composite(saleOrderInformationSection, SWT.NONE);
		soComposite.setLayout(new FormLayout());
		saleOrderInformationSection.setClient(soComposite);
		toolkit.adapt(soComposite);

		final Label saleOrderLabel = toolkit.createLabel(soComposite, "Sales order", SWT.NONE);
		final FormData fd_saleOrderLabel = new FormData();
		fd_saleOrderLabel.bottom = new FormAttachment(0, 17);
		fd_saleOrderLabel.top = new FormAttachment(0, 4);
		fd_saleOrderLabel.right = new FormAttachment(0, 64);
		fd_saleOrderLabel.left = new FormAttachment(0, 10);
		saleOrderLabel.setLayoutData(fd_saleOrderLabel);
		saleOrderLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		saleOrderLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		soSaleOrder = toolkit.createText(soComposite, null);
		final FormData fd_soSaleOrder = new FormData();
		fd_soSaleOrder.bottom = new FormAttachment(0, 23);
		fd_soSaleOrder.top = new FormAttachment(0, 4);
		fd_soSaleOrder.left = new FormAttachment(0, 69);
		soSaleOrder.setLayoutData(fd_soSaleOrder);

		final Label itemCodeLabel = toolkit.createLabel(soComposite, "Item Code", SWT.NONE);
		final FormData fd_itemCodeLabel = new FormData();
		fd_itemCodeLabel.bottom = new FormAttachment(0, 42);
		fd_itemCodeLabel.top = new FormAttachment(0, 29);
		fd_itemCodeLabel.right = new FormAttachment(0, 64);
		fd_itemCodeLabel.left = new FormAttachment(0, 10);
		itemCodeLabel.setLayoutData(fd_itemCodeLabel);
		itemCodeLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		itemCodeLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		soItemCode = toolkit.createText(soComposite, null, SWT.READ_ONLY);
		final FormData fd_soItemCode = new FormData();
		fd_soItemCode.right = new FormAttachment(100, -9);
		fd_soItemCode.bottom = new FormAttachment(0, 48);
		fd_soItemCode.top = new FormAttachment(0, 29);
		fd_soItemCode.left = new FormAttachment(0, 69);
		soItemCode.setLayoutData(fd_soItemCode);

		Label itemNameLabel;
		itemNameLabel = toolkit.createLabel(soComposite, "Item Name", SWT.NONE);
		final FormData fd_itemNameLabel = new FormData();
		fd_itemNameLabel.bottom = new FormAttachment(0, 67);
		fd_itemNameLabel.top = new FormAttachment(0, 54);
		fd_itemNameLabel.right = new FormAttachment(0, 64);
		fd_itemNameLabel.left = new FormAttachment(0, 10);
		itemNameLabel.setLayoutData(fd_itemNameLabel);
		itemNameLabel.setForeground(SWTResourceManager.getColor(0, 0, 255));
		itemNameLabel.setFont(SWTResourceManager.getFont("Tahoma", 8, SWT.NONE));

		soItemName = toolkit.createText(soComposite, null, SWT.READ_ONLY | SWT.WRAP);
		final FormData fd_soItemName = new FormData();
		fd_soItemName.right = new FormAttachment(100, -9);
		fd_soItemName.bottom = new FormAttachment(0, 93);
		fd_soItemName.top = new FormAttachment(0, 54);
		fd_soItemName.left = new FormAttachment(0, 69);
		soItemName.setLayoutData(fd_soItemName);

		Button button;
		button = toolkit.createButton(soComposite, "", SWT.NONE);
		fd_soSaleOrder.right = new FormAttachment(button, 0, SWT.LEFT);
		final FormData fd_button = new FormData();
		fd_button.left = new FormAttachment(100, -35);
		fd_button.right = new FormAttachment(100, -9);
		fd_button.bottom = new FormAttachment(0, 23);
		fd_button.top = new FormAttachment(0, 4);
		button.setLayoutData(fd_button);
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doBrowseAndSelectSalesOrder();
			}
		});
		button.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/viewmag+.png"));

		Section detailSection;
		detailSection = toolkit.createSection(body, Section.TITLE_BAR
				| Section.FOCUS_TITLE);
		final FormData fd_detailSection = new FormData();
		fd_detailSection.bottom = new FormAttachment(100, -40);
		fd_detailSection.right = new FormAttachment(100, 0);
		fd_detailSection.top = new FormAttachment(composite, 5, SWT.BOTTOM);
		fd_detailSection.left = new FormAttachment(0, 0);
		detailSection.setLayoutData(fd_detailSection);
		detailSection.setText("Detail");

		final Composite detailComposite = new Composite(detailSection, SWT.NONE);
		detailComposite.setLayout(new FillLayout());
		detailSection.setClient(detailComposite);
		toolkit.adapt(detailComposite);

		tableViewer = new TableViewer(detailComposite, SWT.FULL_SELECTION | SWT.BORDER);
		table = tableViewer.getTable();
		toolkit.adapt(table, true, true);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		final TableColumn newColumnTableColumn_20 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_20.setWidth(100);
		newColumnTableColumn_20.setText("Date");

		final TableColumn newColumnTableColumn_19 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_19.setWidth(100);
		newColumnTableColumn_19.setText("Due date");

		final TableColumn newColumnTableColumn_18 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_18.setWidth(60);
		newColumnTableColumn_18.setText("Division");

		final TableColumn newColumnTableColumn_16 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_16.setWidth(70);
		newColumnTableColumn_16.setText("Journal");

		final TableColumn newColumnTableColumn_15 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_15.setWidth(60);
		newColumnTableColumn_15.setText("Number");

		final TableColumn newColumnTableColumn_14 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_14.setWidth(50);
		newColumnTableColumn_14.setText("Type");

		final TableColumn newColumnTableColumn_13 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_13.setWidth(60);
		newColumnTableColumn_13.setText("Sub Type");

		final TableColumn newColumnTableColumn_12 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_12.setWidth(80);
		newColumnTableColumn_12.setText("Ledger");

		final TableColumn newColumnTableColumn_11 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_11.setWidth(200);
		newColumnTableColumn_11.setText("Description");

		final TableColumn newColumnTableColumn_10 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_10.setWidth(100);
		newColumnTableColumn_10.setText("Customer");

		final TableColumn newColumnTableColumn_9 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_9.setWidth(100);
		newColumnTableColumn_9.setText("Resource");

		final TableColumn newColumnTableColumn_8 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_8.setWidth(120);
		newColumnTableColumn_8.setText("Your Reference");

		final TableColumn newColumnTableColumn_7 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_7.setWidth(100);
		newColumnTableColumn_7.setText("Our Reference");

		final TableColumn newColumnTableColumn_6 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_6.setWidth(100);
		newColumnTableColumn_6.setText("Currency");

		final TableColumn newColumnTableColumn_5 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_5.setAlignment(SWT.RIGHT);
		newColumnTableColumn_5.setWidth(100);
		newColumnTableColumn_5.setText("Exchange Rate");

		final TableColumn newColumnTableColumn_4 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_4.setAlignment(SWT.RIGHT);
		newColumnTableColumn_4.setWidth(100);
		newColumnTableColumn_4.setText("DebitFC");

		final TableColumn newColumnTableColumn_3 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_3.setAlignment(SWT.RIGHT);
		newColumnTableColumn_3.setWidth(100);
		newColumnTableColumn_3.setText("CreditFC");

		final TableColumn newColumnTableColumn_2 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_2.setAlignment(SWT.RIGHT);
		newColumnTableColumn_2.setWidth(100);
		newColumnTableColumn_2.setText("DebitVND");

		final TableColumn newColumnTableColumn = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn.setAlignment(SWT.RIGHT);
		newColumnTableColumn.setWidth(100);
		newColumnTableColumn.setText("Credit VND");

		final TableColumn newColumnTableColumn_1 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_1.setWidth(100);
		newColumnTableColumn_1.setText("Project Code");

		final TableColumn newColumnTableColumn_17 = new TableColumn(table,
				SWT.NONE);
		newColumnTableColumn_17.setWidth(100);
		newColumnTableColumn_17.setText("Cost Center");
		
		final TableColumn itemCodeColumn = new TableColumn(table,
				SWT.NONE);
		itemCodeColumn.setWidth(100);
		itemCodeColumn.setText("Item Code");
		
		final TableColumn saleOrderColumn = new TableColumn(table,
				SWT.NONE);
		saleOrderColumn.setWidth(100);
		saleOrderColumn.setText("Sale order number");

		tableViewer.setLabelProvider(new PaymentLabelProvider());
		tableViewer.setContentProvider(new AccountReceivableContentProvider());

		final Composite buttonComposite = toolkit.createComposite(body,
				SWT.NONE);
		buttonComposite.setLayout(new FillLayout());
		final FormData fd_buttonComposite = new FormData();
		fd_buttonComposite.left = new FormAttachment(100, -520);
		fd_buttonComposite.top = new FormAttachment(100, -30);
		fd_buttonComposite.bottom = new FormAttachment(100, -5);
		fd_buttonComposite.right = new FormAttachment(100, -5);
		buttonComposite.setLayoutData(fd_buttonComposite);
		toolkit.paintBordersFor(buttonComposite);

		final Button caculateButton = toolkit.createButton(buttonComposite,
				"&Caculate", SWT.NONE);
		caculateButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/mp3player.png"));
		caculateButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				caculateDetail();
			}
		});

		importButton = toolkit.createButton(buttonComposite, "Import", SWT.NONE);
		importButton.setEnabled(false);
		importButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/fileimport.png"));
		importButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				try {
					doImportXMLToExact();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		});

		excelButton = toolkit.createButton(buttonComposite, "Export to E&xcel", SWT.NONE);
		excelButton.setEnabled(false);
		excelButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/excel.gif"));
		excelButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doExport2Excel();
			}
		});

		xmlButton = toolkit.createButton(buttonComposite, "Export to X&ML", SWT.NONE);
		xmlButton.setEnabled(false);
		xmlButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/fileexport.png"));
		xmlButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doExport2XML();
			}
		});

		final Button closeButton = toolkit.createButton(buttonComposite, "Clos&e", SWT.NONE);
		closeButton.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				doClose();
			}
		});
		closeButton.setImage(ResourceManager.getPluginImage(Activator.getDefault(), "icons/actions/shutdown.png"));
		luxPaymnetForm.setText("Account Receivable Detail");
		//
		createActions();
		initializeToolBar();
		initializeMenu();
	}
	
	protected void doImportXMLToExact() throws IOException {
		String fileLocation = Activator.getDefault().getAccountReceivableXMLLocation() + "\\AccountReceivable.xml";
		String serverNameParam = "-r" + Activator.getDefault().getDatabaseProperties()[0];
		String dbNameParam = "-D" + Activator.getDefault().getDatabaseProperties()[2];
		String urlParam;
//		= "-URL" + fileLocation;
		File file = new File(fileLocation);
		if (null != file) {
			try {
				Document document = buildAccountReceivableDocument(list);
				String tempFile = DpUtils
						.getTempFile("AccountReceivableXmlUnicodeRaw");
				XMLWriter writer = new org.dom4j.io.XMLWriter(
						new OutputStreamWriter(new FileOutputStream(tempFile)));
				writer.write(document);
				writer.flush();
				writer.close();
				
				try {
					String xslMapping = Activator.getDefault()
							.getAccountReceivableXSLMapping();
						XMLUtils.transform(tempFile, xslMapping, file);
				} catch (Exception e) {
					MessageDialog.openError(null, "Error", "You may not choose the correct xsl mapping file, please check! " + e.getMessage());
					return;
				}
//				MessageDialog.openInformation(null, "Exportation completed", "The account receivable has been exported to XML format, please find at "
//								+ fileLocation);
			} catch (Exception e) {
				e.printStackTrace();
				MessageDialog.openError(null, "Error", e.getMessage());
			}
		}	
		urlParam = "-URL" + file.getAbsolutePath();
		String[] exactCommand = new String[] {"C:\\Program Files\\Exact Software\\bin\\asimport.exe", serverNameParam, dbNameParam,
				"-u", "-~", "I", urlParam, "-TGLENTRIES", "-0Auto"};
		Runtime.getRuntime().exec(exactCommand);
	}

	protected void doBrowseAndSelectSalesOrder() {
		String sql = "select  SalesOrderNumnber as salesorder, firstitemcode as itemcode, firstitemname as itemname " +
		"from Demand_SalesOrder where contractcode = '" + DpUtils.trim(giContract.getText() + "'");
		SelectSalesOrderInforHeader inforHeader = new SelectSalesOrderInforHeader(Display.getCurrent().getActiveShell(), sql);
		if (inforHeader.open() == Dialog.OK) {
			SalesOrderBean model = inforHeader.getSelectedModel();
			if (null != model) {
				soSaleOrder.setText(model.getSalesOrder());
				soItemCode.setText(model.getItemCode());
				soItemName.setText(model.getItemName());
			}
		}
	}

	private void doClose() {
		setLastestInfor();
		getSite().getWorkbenchWindow().getActivePage().hideView(this);
	}
	
	private String getSavedFileLocation(String[] fileFilterNames, String[] fileFilterTypes) {
		FileDialog fileDialog = new FileDialog(this.getViewSite().getShell(),
				SWT.SAVE);
		fileDialog.setFilterExtensions(fileFilterTypes);
		fileDialog.setFilterNames(fileFilterNames);
		String reportLocation = fileDialog.open();
		return reportLocation;
	}
	
	private Document buildAccountReceivableDocument(
			List<AccountReceivableDetailBean> list) {
		Document document = DocumentHelper.createDocument();
		String xmlDoubleFormat = new String("###############.00");
		double doubleValue = 0;
		Element root = document.addElement("root");
		if (null != list && !list.isEmpty()) {
			for (AccountReceivableDetailBean d : list) {
				Element row = root.addElement("row");
				row.addElement("Division").addText(d.getDivision());
				row.addElement("Date").addText(DpUtils.format(d.getDate()));
				row.addElement("Journal").addText(d.getJournal());
				row.addElement("Number").addText(String.valueOf(d.getNumber()));
				row.addElement("SubType").addText(d.getSubType());
				row.addElement("Type").addText(d.getType());
				row.addElement("Ledger").addText(d.getLedger());
				row.addElement("Description").addText(d.getDescription());
				row.addElement("CostCenter").addText(d.getCostCenter());
				row.addElement("Customer").addText(d.getCustomer());
				row.addElement("Resource").addText(d.getResource());
				row.addElement("ProjectCode").addText(d.getProjectCode());
				row.addElement("ItemCode").addText(d.getItemCode());
				row.addElement("SalesOrder").addText(d.getSalesOrderNumber());
				
				doubleValue = DpUtils.round(d.getDebitVND(), ROUND_SCALE, ROUND_MODE); 
				row.addElement("DebitVND").addText(doubleValue != 0 ? DpUtils.format(doubleValue, xmlDoubleFormat) : "0");
				
				doubleValue = DpUtils.round(d.getCreditVND(), ROUND_SCALE, ROUND_MODE);
				row.addElement("CreditVND").addText(doubleValue != 0 ? DpUtils.format(doubleValue, xmlDoubleFormat) : "0");
				
				row.addElement("Currency").addText(d.getCurrency());
				
				doubleValue = DpUtils.round(d.getDebitFC(), ROUND_SCALE, ROUND_MODE);
				row.addElement("DebitFC").addText(doubleValue != 0 ? DpUtils.format(doubleValue, xmlDoubleFormat) : "0");
				
				doubleValue = DpUtils.round(d.getCreditFC(), ROUND_SCALE, ROUND_MODE);
				row.addElement("CreditFC").addText(doubleValue != 0 ? DpUtils.format(doubleValue, xmlDoubleFormat) : "0");
				
				doubleValue = DpUtils.round(d.getExchangeRate(), ROUND_SCALE, ROUND_MODE);
				row.addElement("ExchangeRate").addText(doubleValue != 0 ? DpUtils.format(doubleValue, xmlDoubleFormat) : "0");
				
				row.addElement("OurReference").addText(d.getOurReference());
				row.addElement("YourReference").addText(d.getYourReference());
				row.addElement("DueDate").addText(
						DpUtils.format(d.getDueDate()));
			}
		}
		return document;
	}
	
	protected void doExport2XML() {
		String fileLocation = getSavedFileLocation(new String[] {"XML File"}, new String[] {"*.xml"});
		File file = new File(fileLocation);
		if (null != file) {
			try {
				Document document = buildAccountReceivableDocument(list);
				String tempFile = DpUtils
						.getTempFile("AccountReceivableXmlUnicodeRaw");
				XMLWriter writer = new org.dom4j.io.XMLWriter(
						new OutputStreamWriter(new FileOutputStream(tempFile)));
				writer.write(document);
				writer.flush();
				writer.close();
				
				try {
					String xslMapping = Activator.getDefault()
							.getAccountReceivableXSLMapping();
					if (file.exists()) {
						if (MessageDialog
								.openQuestion(null, "Question","The file is existed, Do you want to overwrite it?")) {
							XMLUtils.transform(tempFile, xslMapping, file);
						}
					} else {
						XMLUtils.transform(tempFile, xslMapping, file);
					}
				} catch (Exception e) {
					MessageDialog.openError(null, "Error", "You may not choose the correct xsl mapping file, please check! " + e.getMessage());
					return;
				}
				MessageDialog.openInformation(null, "Exportation completed", "The account receivable has been exported to XML format, please find at "
								+ fileLocation);
			} catch (Exception e) {
				e.printStackTrace();
				MessageDialog.openError(null, "Error", e.getMessage());
			}
		}
	}

	protected void doExport2Excel() {
		String reportLocation = getSavedFileLocation(new String[] {"Excel files"}, new String[] {"*.xls"});
		if (null != reportLocation) {
			File file = new File(reportLocation);
			WritableWorkbook workbook;
			try {
				int row = 14;
				workbook = Workbook.createWorkbook(file);
				WritableSheet sheet = workbook.createSheet("Account Receivable", 0);
				setReportHeader(sheet, 0);
				setReportContent(sheet, row);
				workbook.write();
				workbook.close();
				MessageBox box = new MessageBox(this.getViewSite().getShell(),
						SWT.OK | SWT.CANCEL | SWT.ICON_INFORMATION);
				box
						.setMessage("Export completed, click OK to open the result file now or click Cancel to open it manually later");
				int i = box.open();
				if (i == SWT.OK) {
					Runtime.getRuntime().exec("cmd.exe /C \"" + reportLocation + "\"");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} catch (RowsExceededException e) {
				e.printStackTrace();
			} catch (WriteException e) {
				e.printStackTrace();
			}
		}

	}

	private void setReportContent(WritableSheet sheet, int row) {
		if (null != list && !list.isEmpty()) {
			try {
				DateFormat dateFormat = new DateFormat(Activator.getDefault().getDateFormatTypePreferences());
				
				WritableCellFormat normalDateCellFormat = new WritableCellFormat(dateFormat);
				WritableCellFormat normalNumberFormat = new WritableCellFormat(NumberFormats.FORMAT1);
				
				WritableFont font = new WritableFont(WritableFont.ARIAL, 10,
						WritableFont.NO_BOLD);
				//The 4 first rows(yellow background)
				WritableCellFormat yellowTextFormat = new WritableCellFormat(font);
				yellowTextFormat.setBackground(Colour.VERY_LIGHT_YELLOW);
				
				WritableCellFormat dateYellowCellFormat = new WritableCellFormat(dateFormat);
				dateYellowCellFormat.setBackground(Colour.VERY_LIGHT_YELLOW);
				
				WritableCellFormat yellowNumberFormat = new WritableCellFormat(NumberFormats.FORMAT1);
				yellowNumberFormat.setBackground(Colour.VERY_LIGHT_YELLOW);
				
				//The 2 next rows (pink background)
				WritableCellFormat pinkTextFormat = new WritableCellFormat(font);
				pinkTextFormat.setBackground(Colour.PINK2);
				
				WritableCellFormat datePinkCellFormat = new WritableCellFormat(dateFormat);
				datePinkCellFormat.setBackground(Colour.PINK2);
				
				WritableCellFormat pinkNumberFormat = new WritableCellFormat(NumberFormats.FORMAT1);
				pinkNumberFormat.setBackground(Colour.PINK2);
				
				//The 2 next rows (xanh lam)
				WritableCellFormat greenTextFormat = new WritableCellFormat(font);
				greenTextFormat.setBackground(Colour.TURQUOISE);
				
				WritableCellFormat dateGrennCellFormat = new WritableCellFormat(dateFormat);
				dateGrennCellFormat.setBackground(Colour.TURQUOISE);
				
				WritableCellFormat greenNumberFormat = new WritableCellFormat(NumberFormats.FORMAT1);
				greenNumberFormat.setBackground(Colour.TURQUOISE);
				
				int col = 0;
				for (int i = 0; i < list.size(); i++) {
					AccountReceivableDetailBean detail = list.get(i);
					if (i < 4) {
						sheet.addCell(new DateTime(col++, row, detail.getDate(), dateYellowCellFormat));
						sheet.addCell(new DateTime(col++, row, detail.getDueDate(), dateYellowCellFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getDivision(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getJournal(), yellowTextFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getNumber(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getType(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getSubType(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getLedger(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getDescription(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCustomer(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getResource(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getYourReference(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getOurReference(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCurrency(), yellowTextFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getExchangeRate(), yellowNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getDebitFC(), yellowNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getCreditFC(), yellowNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getDebitVND(), yellowNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getCreditVND(), yellowNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getProjectCode(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCostCenter(), yellowTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row++, detail.getItemCode(), yellowTextFormat));
						col = 0;
					} else if (i < 6){
						sheet.addCell(new DateTime(col++, row, detail.getDate(), datePinkCellFormat));
						sheet.addCell(new DateTime(col++, row, detail.getDueDate(), datePinkCellFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getDivision(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getJournal(), pinkTextFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getNumber(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getType(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getSubType(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getLedger(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getDescription(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCustomer(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getResource(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getYourReference(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getOurReference(), pinkTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCurrency(), pinkTextFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getExchangeRate(), pinkNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getDebitFC(), pinkNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getCreditFC(), pinkNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getDebitVND(), pinkNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getCreditVND(), pinkNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getProjectCode(), pinkNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCostCenter(), pinkNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row++, detail.getItemCode(), pinkNumberFormat));
						col = 0;
					} else if (i < 8) {
						sheet.addCell(new DateTime(col++, row, detail.getDate(), dateGrennCellFormat));
						sheet.addCell(new DateTime(col++, row, detail.getDueDate(), dateGrennCellFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getDivision(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getJournal(), greenTextFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getNumber(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getType(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getSubType(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getLedger(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getDescription(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCustomer(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getResource(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getYourReference(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getOurReference(), greenTextFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCurrency(), greenTextFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getExchangeRate(), greenNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getDebitFC(), greenNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getCreditFC(), greenNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getDebitVND(), greenNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getCreditVND(), greenNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getProjectCode(), greenNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCostCenter(), greenNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row++, detail.getItemCode(), greenNumberFormat));
						col = 0;
					} else {
						sheet.addCell(new DateTime(col++, row, detail.getDate(), normalDateCellFormat));
						sheet.addCell(new DateTime(col++, row, detail.getDueDate(), normalDateCellFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getDivision()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getJournal()));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getNumber()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getType()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getSubType()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getLedger()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getDescription()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCustomer()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getResource()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getYourReference()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getOurReference()));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCurrency()));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getExchangeRate(), normalNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getDebitFC(), normalNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getCreditFC(), normalNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getDebitVND(), normalNumberFormat));
						sheet.addCell(new jxl.write.Number(col++, row, detail.getCreditVND(), normalNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getProjectCode(), normalNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row, detail.getCostCenter(), normalNumberFormat));
						sheet.addCell(new jxl.write.Label(col++, row++, detail.getItemCode(), normalNumberFormat));
						col = 0;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void setReportHeader(WritableSheet resultSheet, int i) {
		WritableCellFormat tf;
		WritableCellFormat numberFormat = new WritableCellFormat(
				NumberFormats.FLOAT);
		try {
			WritableFont title = new WritableFont(WritableFont.ARIAL, 20,
					WritableFont.BOLD);
			title.setColour(Colour.BLACK);
			tf = new WritableCellFormat(title);
			tf.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, i++,
					"Account Receivable Detail", tf));
			WritableFont criteriaFont = new WritableFont(WritableFont.ARIAL,
					10, WritableFont.BOLD);
			criteriaFont.setColour(Colour.BLUE);
			WritableCellFormat criteriaFormat = new WritableCellFormat(
					criteriaFont);
			// add an empty row
			i++;
			// Criteria
			WritableFont font = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);
			WritableCellFormat boldFormat = new WritableCellFormat(font);
			boldFormat.setAlignment(Alignment.LEFT);
			
			WritableFont alinRightFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD);
			WritableCellFormat alignRightCellFormat = new WritableCellFormat(alinRightFont);
			alignRightCellFormat.setAlignment(Alignment.RIGHT);
			
			resultSheet.addCell(new jxl.write.Label(0, i, "General Information", boldFormat));
			resultSheet.mergeCells(0, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i,
					"Installment Condition", boldFormat));
			resultSheet.mergeCells(4, i, 5, i);
			resultSheet.addCell(new jxl.write.Label(6, i, "Invoice Amount", boldFormat));
			resultSheet.mergeCells(6, i, 7, i);
			resultSheet.addCell(new jxl.write.Label(8, i++,
					"Ledger Information", boldFormat));
			resultSheet.mergeCells(8, i - 1, 9, i  -1 );
			
			DateFormat format = new DateFormat(Activator.getDefault()
					.getDateFormatTypePreferences());
			WritableCellFormat dateFormat = new WritableCellFormat(format);
			//1st header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Contract",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils
					.trim(giContract.getText())));
			resultSheet.mergeCells(1, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "Date",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.DateTime(5, i, ciDate.getValue(),
					dateFormat));
			resultSheet.addCell(new jxl.write.Label(6, i, "Revenue",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(7, i,
					((Number) iaRevenueNumberFormatter.getValue())
							.doubleValue(), numberFormat));
			resultSheet.addCell(new jxl.write.Label(8, i, "Revenue",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(9, i++, DpUtils
					.trim(liRevenue.getText())));
			//2nd header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Customer Code",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils
					.trim(giCustomerCode.getText())));
			resultSheet.mergeCells(1, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "First due date",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.DateTime(5, i, ciDueDate
					.getValue(), dateFormat));
			resultSheet.addCell(new jxl.write.Label(6, i, "VAT Amount",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(7, i,
					((Number) iaVATAmoutFormatText.getValue()).doubleValue(),
					numberFormat));
			resultSheet.addCell(new jxl.write.Label(8, i, "VAT Amount",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(9, i++, DpUtils
					.trim(liVATAmount.getText())));
			//3rd header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Customer Name",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils
					.trim(giCustomerName.getText())));
			resultSheet.mergeCells(1, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "Installment Period",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(5, i,
					((Number) ciInstallmentPeriodFormatText.getValue())
							.doubleValue(), numberFormat));
			resultSheet.addCell(new jxl.write.Label(6, i, "Interest",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(7, i,
					((Number) iaInterstFormatText.getValue()).doubleValue(),
					numberFormat));
			resultSheet.addCell(new jxl.write.Label(8, i, "Interest",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(9, i++, DpUtils
					.trim(liInterest.getText())));
			//4th header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Cost center",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils
					.trim(giCostCenter.getText())));
			resultSheet.mergeCells(1, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "VAT Percentage",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(5, i,
					((Number) ciVATFormatText.getValue()).doubleValue(),
					numberFormat));
			resultSheet.addCell(new jxl.write.Label(6, i, "Booking fee",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(7, i,
					((Number) iaBookingFeeFormattedText.getValue())
							.doubleValue(), numberFormat));
			resultSheet.addCell(new jxl.write.Label(8, i, "Booking fee",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(9, i++, DpUtils
					.trim(liBookingFee.getText())));
			//5th header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Division",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils
					.trim(giDivision.getText())));
			resultSheet.mergeCells(1, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "Currency",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i, DpUtils
					.trim(ciCurrency.getText()), alignRightCellFormat));
			resultSheet.addCell(new jxl.write.Label(6, i, "Down Payment",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(7, i,
					((Number) iaDownpaymentFormattedText.getValue())
							.doubleValue(), numberFormat));
			resultSheet.addCell(new jxl.write.Label(8, i, "Down Payment",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(9, i++, DpUtils
					.trim(liDownPayment.getText())));
			//6th header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Invoice Ref",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils
					.trim(giDivision.getText())));
			resultSheet.mergeCells(1, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "Exchange Rate",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(5, i,
					((Number) ciEchangeFormatText.getValue()).doubleValue(),
					numberFormat));
			resultSheet.addCell(new Blank(6, i));
			resultSheet.addCell(new Blank(7, i++));
			//7th header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Journal code",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils
					.trim(giJournalCode.getText())));
			resultSheet.mergeCells(1, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "Resource",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i, DpUtils
					.trim(ciResource.getText()), alignRightCellFormat));
			resultSheet.addCell(new jxl.write.Label(6, i, "Invoice Amount",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(7, i++, DpUtils
					.parse(iaInvoiceAmountResult.getText()), numberFormat));
			//8th header row
			resultSheet.addCell(new jxl.write.Label(0, i, "Suspense",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(1, i, DpUtils
					.trim(giSuspense.getText())));
			resultSheet.mergeCells(1, i, 3, i);
			resultSheet.addCell(new jxl.write.Label(4, i, "Current Our Ref",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(5, i, DpUtils
					.trim(ciCurrOurRef.getText()), alignRightCellFormat));
			resultSheet.addCell(new jxl.write.Label(6, i, "Installment Amount",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Number(7, i, DpUtils
					.parse(iaInstallmentAmountResult.getText()), numberFormat));
			resultSheet.addCell(new jxl.write.Label(8, i, "Installment Amount",
					criteriaFormat));
			resultSheet.addCell(new jxl.write.Label(9, i++, DpUtils.trim(liInstallmentAmount.getText())));
			//Detail row header
			WritableFont underLineFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, true, UnderlineStyle.SINGLE);
			WritableCellFormat undeLineFontCellFormat = new WritableCellFormat(underLineFont);
			undeLineFontCellFormat.setAlignment(Alignment.LEFT);
			resultSheet.addCell(new jxl.write.Label(0, ++i,
					"Detail Information", undeLineFontCellFormat));

			// set font and background color
			WritableFont header = new WritableFont(WritableFont.ARIAL, 10,
					WritableFont.BOLD);
			header.setColour(Colour.WHITE);
			WritableCellFormat hf = new WritableCellFormat(header);
			hf.setBackground(Colour.BLUE);
			hf.setAlignment(Alignment.CENTRE);
			hf.setVerticalAlignment(VerticalAlignment.CENTRE);
			hf.setWrap(true);
			int col = 0;
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, ++i, "Date", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Due Date", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Division", hf));
			resultSheet.setColumnView(col, 10);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Journal", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Number", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Type", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "SubType", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Ledger", hf));
			resultSheet.setColumnView(col, 25);
			resultSheet
					.addCell(new jxl.write.Label(col++, i, "Description", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Customer", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Resource", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Your Reference",
					hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "OurReference",
					hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Currency", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Exchange Rate",
					hf));
			resultSheet.setColumnView(col, 20);
			resultSheet.addCell(new jxl.write.Label(col++, i, "DebitFC", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "CreditFC", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "DebitVND", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "CreditVND", hf));
			resultSheet.setColumnView(col, 15);
			resultSheet.addCell(new jxl.write.Label(col++, i, "Project Code",
					hf));
			resultSheet.setColumnView(col, 20);
			resultSheet
					.addCell(new jxl.write.Label(col++, i, "Cost Center", hf));
			resultSheet.setColumnView(col, 20);
			resultSheet
			.addCell(new jxl.write.Label(col++, i, "Item Code", hf));
	resultSheet.setColumnView(col, 20);

		} catch (WriteException e) {
			e.printStackTrace();
		}
	}

	private boolean doValidate() {
		Color orange = new Color(null, 255, 200, 100);
		Color white = new Color(null, 255, 255, 255);
		if (DpUtils.length(giContract.getText()) == 0) {
			MessageDialog.openError(null, "Error", "Contract number cannot be empty");
			giContract.setBackground(orange);
			giContract.setFocus();
			return false;
		} else if (!Validator.isValidContractNumber(giContract.getText().trim())) {
			MessageDialog.openError(null, "Error", "Contract number is not valid");
			giContract.setBackground(orange);
			giContract.setFocus();
			return false;
		} else {
			giContract.setBackground(white);
		}
		if (DpUtils.length(giInvoiceRef.getText()) == 0) {
			MessageDialog.openError(null, "Error", "Plan Invoice Ref cannot be empty");
			giInvoiceRef.setBackground(orange);
			giInvoiceRef.setFocus();
			return false;
		} else {
			giInvoiceRef.setBackground(white);
		}
		if (!Validator.isValidJournalCode(giJournalCode.getText().trim())) {
			MessageDialog.openError(null, "Error", "Journal code is not valid");
			giJournalCode.setBackground(orange);
			giJournalCode.setFocus();
			return false;
		} else {
			giJournalCode.setBackground(white);
		}
		if (((Number)ciInstallmentPeriodFormatText.getValue()).intValue() < 1) {
			MessageDialog.openError(null, "Error", "Installment Period cannot be less than 1");
			ciInstallmentPeriod.setBackground(orange);
			ciInstallmentPeriod.setFocus();
			return false;
		} else {
			ciInstallmentPeriod.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liBookingFee.getText().trim())) {
			MessageDialog.openError(null, "Error", "Booking fee account is not valid");
			liBookingFee.setBackground(orange);
			liBookingFee.setFocus();
			return false;
		} else {
			liBookingFee.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liDownPayment.getText().trim())) {
			MessageDialog.openError(null, "Error", "Downpayment account is not valid");
			liDownPayment.setBackground(orange);
			liDownPayment.setFocus();
			return false;
		} else {
			liDownPayment.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liInstallmentAmount.getText().trim())) {
			MessageDialog.openError(null, "Error", "InstallmentAmount account is not valid");
			liInstallmentAmount.setBackground(orange);
			liInstallmentAmount.setFocus();
			return false;
		} else {
			liInstallmentAmount.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liInterest.getText().trim())) {
			MessageDialog.openError(null, "Error", "Interest account is not valid");
			liInterest.setBackground(orange);
			liInterest.setFocus();
			return false;
		} else {
			liInterest.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liRevenue.getText().trim())) {
			MessageDialog.openError(null, "Error", "Revenue account is not valid");
			liRevenue.setBackground(orange);
			liRevenue.setFocus();
			return false;
		} else {
			liRevenue.setBackground(white);
		}
		if (!Validator.isValidAccountNumber(liVATAmount.getText().trim())) {
			MessageDialog.openError(null, "Error", "VAT Amount account is not valid");
			liVATAmount.setBackground(orange);
			liVATAmount.setFocus();
			return false;
		} else {
			liVATAmount.setBackground(white);
		}
		if (Validator.isMoreThanOneSalesOrder(giContract.getText().trim())) {
			if (MessageDialog.openQuestion(null, "Confirmation", "There was more than 1 sales order have been entered for this contract. Continue?")) {
				return true;
			} 
			return false;
		}
		if (soItemCode.getText() == null || soItemCode.getText().equals("")) {
			if (MessageDialog.openQuestion(null, "Confirmation", " Item code is blank. Continue?")) {
				return true;
			}
			return false;
		}
		return true;
	}

	protected void caculateDetail() {
		try {
			list = new ArrayList<AccountReceivableDetailBean>();
			if (doValidate()) {
				Number period = (Number) ciInstallmentPeriodFormatText
						.getValue();
				int length = 11 + 2 * period.intValue();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(ciDueDate.getValue());
//				Integer detailCurrOurRef = new Integer(0);
				double value = DpUtils.parse(iaInstallmentAmountResult.getText());
				int installmentPeriod = ((Number) ciInstallmentPeriodFormatText
						.getValue()).intValue();
				int descriptionIndex = 0;
				double exchangeRate = ((Number) ciEchangeFormatText.getValue())
						.doubleValue();
				double doubleValue = 0;
				//revenue dung de tinh cho record thu 4
				double revenueValue = 0;
				//sai so cua debitFC (dung de tinh don cho thang cuoi cung , muc dich la lam cho total duoc balance sau khi chia và cong nguoc lại)
				double sumE = 0;
				Integer currOurRef = 0;
				currOurRef = Integer.valueOf(ciCurrOurRef
							.getText()) + 1;
				for (int i = 0; i < length; i++) {
					AccountReceivableDetailBean detail = new AccountReceivableDetailBean();
					detail.setDate(ciDate.getValue());
					detail.setDivision(giDivision.getText());
					detail.setJournal(giJournalCode.getText());
					detail.setNumber(i + 1);
					detail.setType("N");
					detail.setCustomer(giCustomerCode.getText());
					detail.setResource(ciResource.getText());
					detail.setYourReference(giInvoiceRef.getText());
					detail.setExchangeRate(exchangeRate);
					detail.setProjectCode(giContract.getText());
					detail.setCostCenter(giCostCenter.getText());
					detail.setItemCode(soItemCode.getText());
					detail.setSalesOrderNumber(soSaleOrder.getText());
					detail.setCurrency(ciCurrency.getText());
					// yellow rows
					if (i < 7) {
						detail.setDueDate(ciDate.getValue());
						detail.setSubType("N");
						detail.setOurReference(String.valueOf(currOurRef));
						switch (i) {
						case 0:
							detail.setLedger(liRevenue.getText());
							detail.setDescription("Revenue of contract "
									+ giContract.getText());
							doubleValue = ((Number) iaRevenueNumberFormatter.getValue()).doubleValue();
							detail.setCreditFC(DpUtils.round(doubleValue, ROUND_SCALE, ROUND_MODE));
							detail.setCreditVND(DpUtils.round(detail.getCreditFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
							revenueValue = detail.getCreditVND();
							System.out.println("Dong 0:" +revenueValue);
							break;
						case 1:
							detail.setLedger(liExchangeRate.getText());
							detail.setDescription("VAT output of contract "
									+ giContract.getText());
							doubleValue = ((Number) iaVATAmoutFormatText.getValue()).doubleValue();
							detail.setCreditFC(DpUtils.round(doubleValue, ROUND_SCALE, ROUND_MODE));
							detail.setCreditVND(DpUtils.round(detail.getCreditFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
							break;
						case 2:
							detail.setLedger(liInterest.getText());
							detail.setDescription("Interest of contract "
									+ giContract.getText());
							doubleValue = ((Number) iaInterstFormatText.getValue()).doubleValue();
							detail.setCreditFC(DpUtils.round(doubleValue, ROUND_SCALE, ROUND_MODE));
							detail.setCreditVND(DpUtils.round(detail.getCreditFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
							break;
						case 3:
							detail.setLedger(giSuspense.getText());
							detail.setDescription("Suspense of contract "
									+ giContract.getText());
							double revenue = ((Number) iaRevenueNumberFormatter.getValue()).doubleValue();
							revenue = DpUtils.round(revenue, ROUND_SCALE, ROUND_MODE);
							double vatAmount = ((Number) iaVATAmoutFormatText.getValue()).doubleValue();
							vatAmount = DpUtils.round(vatAmount, ROUND_SCALE, ROUND_MODE);
							double interest = ((Number) iaInterstFormatText.getValue()).doubleValue();
							interest = DpUtils.round(interest, ROUND_SCALE, ROUND_MODE);
							doubleValue = revenue + vatAmount + interest; 
							detail.setDebitFC(doubleValue);
							detail.setDebitVND(DpUtils.round(detail.getDebitFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
							break;
						case 4:
							detail.setDescription("VAT output of contract "
									+ giContract.getText());
							detail.setOurReference(String.valueOf(++currOurRef));
							detail.setLedger(liExchangeRate.getText());
							detail.setCurrency("VND");
							detail.setDebitVND(0);
							detail.setExchangeRate(1);
							detail.setCreditVND(DpUtils.round(revenueValue, VND_ROUND_SCALE, ROUND_MODE));
							System.out.println("Dong 4:" +detail.getCreditVND());
							break;
						case 5:
							detail.setDescription("VAT output of contract "
									+ giContract.getText());
							detail.setOurReference(String.valueOf(currOurRef));
							detail.setLedger(liVATAmount.getText());
							detail.setCurrency("VND");
							detail.setExchangeRate(1);
							detail.setDebitVND(0);
							doubleValue = DpUtils.round(revenueValue / ((Number)ciVATFormatText.getValue()).doubleValue(), VND_ROUND_SCALE, ROUND_MODE);
							detail.setCreditVND(doubleValue);
							System.out.println("Dong 5:" +doubleValue);
							break;
						case 6:
							detail.setDescription("VAT output of contract "
									+ giContract.getText());
							detail.setOurReference(String.valueOf(currOurRef++));
							detail.setLedger(liExchangeRate.getText());
							detail.setCurrency("VND");
							detail.setExchangeRate(1);
							System.out.println("Sai so:" +(revenueValue + doubleValue));
							detail.setDebitVND(revenueValue + doubleValue);
							break;	
						}
					} else if (6 < i && i < 9) {
						// 2 pink rows
						detail.setDueDate(ciDate.getValue());
						detail.setSubType("K");
						switch (i) {
						case 7:
							detail.setOurReference(String.valueOf(currOurRef));
							detail.setLedger(liBookingFee.getText());
							detail.setDescription("Booking fee of contract "
									+ giContract.getText());
							doubleValue = ((Number) iaBookingFeeFormattedText.getValue()).doubleValue();
							detail.setDebitFC(DpUtils.round(doubleValue, ROUND_SCALE, ROUND_MODE));
							detail.setDebitVND(DpUtils.round(detail.getDebitFC()* exchangeRate, 0, ROUND_MODE));
							break;
						case 8:
							detail.setOurReference(String.valueOf(currOurRef++));
							detail.setLedger(giSuspense.getText());
							detail.setDescription("Suspense of contract "
									+ giContract.getText());
							doubleValue = ((Number) iaBookingFeeFormattedText.getValue()).doubleValue();
							detail.setCreditFC(DpUtils.round(doubleValue, ROUND_SCALE, ROUND_MODE));
							detail.setCreditVND(DpUtils.round(detail.getCreditFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
						default:
							break;
						}

					} else {
						// 2 blue rows
						detail.setDueDate(ciDate.getValue());
						detail.setSubType("K");
						switch (i) {
						case 9:
							detail.setOurReference(String.valueOf(currOurRef));
							detail.setLedger(liDownPayment.getText());
							detail.setDescription("Down payment of contract "
									+ giContract.getText());
							doubleValue = ((Number) iaDownpaymentFormattedText.getValue()).doubleValue();
							detail.setDebitFC(DpUtils.round(doubleValue, ROUND_SCALE, ROUND_MODE));
							detail.setDebitVND(detail.getDebitFC()
									* exchangeRate);
							break;
						case 10:
							detail.setOurReference(String.valueOf(currOurRef));
							detail.setLedger(giSuspense.getText());
							detail.setDescription("Suspense of contract "
									+ giContract.getText());
							doubleValue = ((Number) iaDownpaymentFormattedText.getValue()).doubleValue();
							detail.setCreditFC(DpUtils.round(doubleValue, ROUND_SCALE, ROUND_MODE));
							detail.setCreditVND(DpUtils.round(detail.getCreditFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
							break;
						case 11:
							// last rows, marks the first row of details
							detail.setOurReference(String.valueOf(++currOurRef));
							detail.setSubType("K");
							detail.setDueDate(calendar.getTime());
							detail.setLedger(liInstallmentAmount.getText());
							descriptionIndex = i - 10;
							detail.setDescription("Receivable "
									+ String.valueOf(descriptionIndex)
									+ " of contract " + giContract.getText());
							detail.setDebitFC(DpUtils.round(value / installmentPeriod, FinanceForPayment.ROUND_SCALE, FinanceForPayment.ROUND_MODE));
//							sumE += detail.getDebitFC();
							detail.setDebitVND(DpUtils.round(detail.getDebitFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
							break;
						default:
							// last rows
							detail.setSubType("K");
							if (i % 2 == 0) {
								detail.setOurReference(String.valueOf(currOurRef));
								descriptionIndex += 1;
								detail.setLedger(giSuspense.getText());
								detail.setDescription("Suspense of contract "
										+ giContract.getText());
//								detailCurrOurRef++;
								//do^`n sai số vào tháng cuối cho Debit
								if (i != length -1) {
									detail.setCreditFC(DpUtils.round(value / installmentPeriod, FinanceForPayment.ROUND_SCALE, FinanceForPayment.ROUND_MODE));
									sumE += detail.getCreditFC();
								} else {
									detail.setCreditFC(value - sumE);
								}
								detail.setCreditVND(DpUtils.round(detail.getCreditFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
							} else {
								calendar.add(Calendar.MONTH, 1);
								detail.setLedger(liInstallmentAmount.getText());
								detail.setDescription("Receivable "
										+ String.valueOf(descriptionIndex)
										+ " of contract "
										+ giContract.getText());
								detail.setOurReference(String.valueOf(++currOurRef));
								//dồn sai số vào tháng cuối cho Credit
								if (i == length -2) {
									//Truong hop installment period ==  1 thi sum == value ==> set gia tri value
									if (value == sumE) {
										detail.setDebitFC(value);
									} else {
										detail.setDebitFC(value - sumE);
									}
								} else {
									detail.setDebitFC(DpUtils.round(value / installmentPeriod, FinanceForPayment.ROUND_SCALE, FinanceForPayment.ROUND_MODE));
								}
								detail.setDebitVND(DpUtils.round(detail.getDebitFC()* exchangeRate, VND_ROUND_SCALE, ROUND_MODE));
							}
							detail.setDueDate(calendar.getTime());
							break;
						}
					}
					list.add(detail);
				}
				importButton.setEnabled(!list.isEmpty());
				excelButton.setEnabled(!list.isEmpty());
				xmlButton.setEnabled(!list.isEmpty());
				tableViewer.setInput(list);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	protected void refreshAmount() {
		NumberFormat nf = new DecimalFormat("###,###,###,###.00");
		iaInvoiceAmountResult.setText(DpUtils.format(caculateInvoiceAmount(), nf));
		iaInstallmentAmountResult.setText(DpUtils.format(caculateInstallmentAmount(), nf));
	}

	private void caculateVATAmount() {
		Number revenue = (Number) iaRevenueNumberFormatter.getValue();
		Number vatPer = (Number) ciVATFormatText.getValue();
		if (vatPer.doubleValue() != 0) {
			double vatAmount = revenue.doubleValue() / vatPer.doubleValue();
			iaVATAmoutFormatText.setValue(vatAmount);
		}
	}

	private double caculateInvoiceAmount() {
		Number revenue = (Number) iaRevenueNumberFormatter.getValue();
		Number vatAmount = (Number) iaVATAmoutFormatText.getValue();
		Number interest = (Number) iaInterstFormatText.getValue();
		return revenue.doubleValue() + vatAmount.doubleValue() + interest.doubleValue();
	}

	private double caculateInstallmentAmount() {
		Number bookingFee = (Number) iaBookingFeeFormattedText.getValue();
		Number downPaymnet = (Number) iaDownpaymentFormattedText.getValue();
		return caculateInvoiceAmount()
				- (bookingFee.doubleValue() + downPaymnet.doubleValue());
	}

	private String getCurrentOurRef() {
		String sql = "SELECT MAX(g.faktuurnr) AS CurrentOurRef FROM dbo.gbkmut g INNER JOIN" +
					 " dbo.dagbk d ON g.dagbknr = d.dagbknr WHERE (d.type_dgbk = 'M')";
		QueryRunner runner = new QueryRunner(DpUtils.getDataSource());
		try {
			return (String) runner.query(sql, new ResultSetHandler() {

				public Object handle(ResultSet rs) throws SQLException {
					String currentOurRef = "";
					while (rs.next()) {
						currentOurRef = rs.getString("CurrentOurRef");
					}
					return currentOurRef;
				}

			});
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	protected void doFillContractInforAndClearOldResult() {
		//clear old result if any
		if (null != list) {
			list.clear();
			tableViewer.setInput(list);
			excelButton.setEnabled(!list.isEmpty());
			xmlButton.setEnabled(!list.isEmpty());
		}
		String sql = "select customercode, customername, costcentercode, installmentperiod from Demand_ContractInformation where contractnumber = ?";
		QueryRunner runner = new QueryRunner(DpUtils.getDataSource());
		try {
			runner.query(sql, DpUtils.trim(giContract.getText()),
					new ResultSetHandler() {

						public Object handle(ResultSet rs) throws SQLException {
							String info = "";
							while (rs.next()) {
								info = rs.getString("customercode");
								giCustomerCode.setText(DpUtils.trim(info));
								info = rs.getString("customername");
								giCustomerName.setText(DpUtils.trim(info));
								info = rs.getString("costcentercode");
								giCostCenter.setText(DpUtils.trim(info));
								ciInstallmentPeriodFormatText.setValue(rs.getInt("installmentPeriod"));
								break;
							}
							return null;
						}

					});
		} catch (SQLException e) {
			e.printStackTrace();
			MessageDialog.openError(null, "Error", e.getMessage());
		}
	}

	
	private void doFillSalesOrderInformation() {
		String sql = "select  SalesOrderNumnber as salesorder, firstitemcode as itemcode, firstitemname as itemname, linenumber " +
				"from Demand_SalesOrder where contractcode = ?";
		QueryRunner runner = new QueryRunner(DpUtils.getDataSource());
		try {
			runner.query(sql, DpUtils.trim(giContract.getText()), new ResultSetHandler() {
				int salesOrder = 0;
				String itemCode = "";
				String itemName = "";
				public Object handle(ResultSet rs) throws SQLException {
					int maxSalesOrder;
					while (rs.next()) {
						maxSalesOrder = rs.getInt("salesorder");
						if (maxSalesOrder > salesOrder) {
							salesOrder = maxSalesOrder;
							if (rs.getInt("linenumber") == 1) {
								itemCode = rs.getString("itemcode");
								itemName = rs.getString("itemname");
							} else {
								itemCode = "";
								itemName = "";
							}
						}
					}
					soSaleOrder.setText(String.valueOf(salesOrder));
					soItemCode.setText(itemCode);
					soItemName.setText(itemName);
					return null;
				}

			});
		} catch (Exception e) {
			e.printStackTrace();
			MessageDialog.openError(null, "Error", e.getMessage());
		}
	}
	/**
	 * Create the actions
	 */
	private void createActions() {
		// Create the actions
	}

	/**
	 * Initialize the toolbar
	 */
	private void initializeToolBar() {
		IToolBarManager tbm = getViewSite().getActionBars().getToolBarManager();
	}

	/**
	 * Initialize the menu
	 */
	private void initializeMenu() {
		IMenuManager manager = getViewSite().getActionBars().getMenuManager();
	}

	@Override
	public void setFocus() {
		// Set the focus
	}
	
	private void setLastestInfor() {
//		Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.ACCOUNT_RECEIVABLE_DIVISION, giDivision.getText());
//		Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.ACCOUNT_RECEIVABLE_JOURNAL_CODE, giJournalCode.getText());
//		Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.ACCOUNT_RECEIVABLE_REVENUE, liRevenue.getText());
//		Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.ACCOUNT_RECEIVABLE_VAT_AMOUNT, liVATAmount.getText());
//		Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.ACCOUNT_RECEIVABLE_INTEREST, liInterest.getText());
//		Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.ACCOUNT_RECEIVABLE_BOOKING_FEE, liBookingFee.getText());
//		Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.ACCOUNT_RECEIVABLE_DOWNPAYMENT, liDownPayment.getText());
//		Activator.getDefault().getPreferenceStore().setValue(PreferenceConstants.ACCOUNT_RECEIVABLE_INSTALLMENT_AMOUNT, liInstallmentAmount.getText());
	}
	
	private class PaymentLabelProvider implements ITableLabelProvider,
			IColorProvider {

		private Color yellow = new Color(null, 255, 255, 168);
		private Color pink = new Color(null, 255, 187, 255);
		private Color blue = new Color(null, 183, 255, 255);
		private Color orange = new Color(null, 250, 220, 165);

		public Image getColumnImage(Object element, int columnIndex) {
			return null;
		}

		public String getColumnText(Object element, int columnIndex) {
			AccountReceivableDetailBean details = (AccountReceivableDetailBean) element;
			String format = "###,###,###,###.00";
			String formatVND = "###,###,###,###,###";
			double value = 0;
			switch (columnIndex) {
			case 0:
				return DpUtils.format(details.getDate());
			case 1:
				return DpUtils.format(details.getDueDate());
			case 2:
				return DpUtils.trim(details.getDivision());
			case 3:
				return DpUtils.trim(details.getJournal());
			case 4:
				return String.valueOf(details.getNumber());
			case 5:
				return DpUtils.trim(details.getType());
			case 6:
				return DpUtils.trim(details.getSubType());
			case 7:
				return DpUtils.trim(details.getLedger());
			case 8:
				return DpUtils.trim(details.getDescription());
			case 9:
				return DpUtils.trim(details.getCustomer());
			case 10:
				return DpUtils.trim(details.getResource());
			case 11:
				return DpUtils.trim(details.getYourReference());
			case 12:
				return DpUtils.trim(details.getOurReference());
			case 13:
				return DpUtils.trim(details.getCurrency());
			case 14:
				value = details.getExchangeRate();
				return value != 0 ? DpUtils.format(value, format) : "";
			case 15:
				value = details.getDebitFC();
				return value != 0 ? DpUtils.format(value, format) : "";
			case 16:
				value = details.getCreditFC();
				return value != 0 ? DpUtils.format(value, format) : "";
			case 17:
				value = details.getDebitVND();
				return value != 0 ? DpUtils.format(value, formatVND) : "";
			case 18:
				value = details.getCreditVND();
				return value != 0 ? DpUtils.format(value, formatVND) : "";
			case 19:
				return DpUtils.trim(details.getProjectCode());
			case 20:
				return DpUtils.trim(details.getCostCenter());
			case 21:
				return DpUtils.trim(details.getItemCode());	
			case 22:
				return DpUtils.trim(details.getSalesOrderNumber());
			default:
				break;
			}
			return null;
		}

		public void addListener(ILabelProviderListener listener) {
		}

		public void dispose() {
		}

		public boolean isLabelProperty(Object element, String property) {
			return false;
		}

		public void removeListener(ILabelProviderListener listener) {
		}

		@SuppressWarnings("unchecked")
		public Color getBackground(Object element) {
			ArrayList<AccountReceivableDetailBean> list = (ArrayList<AccountReceivableDetailBean>) tableViewer.getInput();
			int index = list.indexOf(element);
			if (index < 4) {
				return yellow;
			} else if (index < 7){
				return orange;
			} else if (index < 9) {
				return pink;
			} else if (index < 11) {
				return blue;
			}
			return null;
		}

		public Color getForeground(Object element) {
			return null;
		}
	}
	
	public static void main(String[] args) {
		try {
			System.out.println("Chay di con");
//			String fileLocation = Activator.getDefault().getAccountReceivableXMLLocation() + "\\AccountReceivable.xml";
//			String serverNameParam = "-r" + Activator.getDefault().getDatabaseProperties()[0];
//			String dbNameParam	  = "-D" + Activator.getDefault().getDatabaseProperties()[2]; 
			String fileLocation = "C:\\Documents and Settings";
			String serverNameParam = "-rdemand-thinhnt";
			String dbNameParam = "-D530";
			String urlParam 	  = "-URL" + fileLocation;
			String[] exactCommand = new String[] {"C:\\Program Files\\Exact Software\\bin\\asimport.exe", serverNameParam, dbNameParam,
					"-u", "-~", "I", urlParam, "-TGLENTRIES", "-0Auto"};
			Runtime.getRuntime().exec(exactCommand);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
